package sk.naive.talker.adapter;

import java.util.*;

/**
 * ItemTagProcessor.
 * @author <a href="mailto:virgo@naive.deepblue.sk">Richard "Virgo" Richter</a>
 * @version $Revision: 1.5 $ $Date: 2005/01/09 20:28:14 $
 */
public class ItemTagProcessor implements TagProcessor {
	public String process(MessageProcessingContext ctx, String params) throws TagProcessorException {
		MessageProcessingContext.MessageConsumer consumer = ctx.getConsumer();
		if (consumer instanceof ItemConsumer) {
			((ItemConsumer) consumer).itemComplete();
		} else {
			ctx.switchConsumer(new ItemConsumer(consumer.result()), false);
		}
		return null;
	}

	public static class ItemConsumer extends MessageProcessingContext.BufferMessageConsumer {
		private List<String> items = new ArrayList<String>();
		private String preText;

		public ItemConsumer(String oldConsumerResult) {
			this.preText = oldConsumerResult;
		}

		public String result() {
			return preText;
		}

		public void itemComplete() {
			items.add(buffer.toString());
			buffer.setLength(0);
		}

		public List<String> items() {
			if (buffer.length() > 0) {
				itemComplete();
			}
			return items;
		}
	}
}
